package com.wanxi.dangdang.mapper;

import com.wanxi.dangdang.model.pojo.Role;
import com.wanxi.dangdang.model.vo.RoleFindByIdVo;
import com.wanxi.dangdang.model.vo.RolePermissionVo;
import com.wanxi.dangdang.model.vo.RoleVo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @Author: 吕永杰
 * @Description:
 * @Date: Created in 2021/9/1
 * @Version: 1.0
 */
@Repository
public interface RoleMapper {

    //检验是否存在
    @Select("select name from role where name=#{name}")
    String checkName(String name);

    @Select("select r.* from admin_role_relation ar left join role r on r.id=ar.role_id where ar.admin_id=#{id}")
    List<Role> findRolesByUserId(Long id);

    @Insert("insert into role (name,description,create_time,update_time) value (#{name},#{description},NOW(),NOW())")
    void add(Role role);

    @Select("select id,name,description from role where id = #{id}")
    Role findById(Long id);

    @Select("select id,name,description from role where delete_status=0")
    List<RoleFindByIdVo> findPage(RoleVo roleVo);

    @Update("update role set name=#{name},description=#{description},update_time=NOW() where id=#{id}")
    void updateById(Role role);

    @Update("update role set delete_status=1,update_time=NOW() where id=#{id}")
    void deleteById(Long id);

    //删除关于role_permission_relation中间表的数据
    @Delete("Delete from role_permission_relation where role_id=#{id}")
    void deleteRolePermissionById(Long id);

    //删除关于admin_role_relation中间表的数据
    @Delete("Delete from admin_role_relation where role_id=#{id}")
    void deleteAdminRoleById(Long id);

    @Insert({
            "<script>",
            "insert into role_permission_relation (role_id, permission_id,create_time,update_time) values ",
            // collection 和 value对应   item代表循环中List的这一项IpMap
            "<foreach collection='permissions' item='permissionId' index='index' separator=','>",
            "(#{id}, #{permissionId},NOW(),NOW())",
            "</foreach>",
            "</script>"
    })
    void updatePermissionsById(RolePermissionVo rolePermissionVo);
}
